import base64
import json
import json
import logging as log

import binascii
import uuid

from app.controllers.base_controller import BaseController
from app.libs.util import check_param
from app.models.models import Users, RechargeCard, Notice

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.ERROR)
import logging as log
import xxtea

UMI_SESSION_SECRET = '45222e00'

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


def encrept(data):
    # print(data)
    return base64.b64encode(xxtea.encrypt(data, UMI_SESSION_SECRET)).decode('utf8')


class Login(BaseController):

    def get(self):
        # 获取参数
        did = self.get_argument('did', '')
        if check_param([did]):
            self.render_json(code=10003, msg='参数不全')
            return
        user = Users.objects.filter(did=did).first()
        if not user:
            user = Users.objects.create(did=did,amount=1)

        encrypt_data = encrept(json.dumps(user.to_dict()))
        notices = [k.to_dict() for k in Notice.objects.all()]
        extra = dict(
            version='4.6.8',
            build='10870157',
        )

        self.render_json(data=encrypt_data, notice=notices, recharge_url='http://t.cn/EG4Pbyr', extra=extra)
        return


class GenerateCard(BaseController):
    def get(self):
        type = self.get_argument('type', '')
        num = self.get_argument('num', '')
        if check_param([type, num]):
            self.render_json(code=10003, msg='参数不全')
            return
        for i in range(int(num)):
            recharge_card = RechargeCard.objects.create(amount=int(type))
            card_no = uuid.uuid3(uuid.NAMESPACE_DNS, str(recharge_card.id)).hex
            recharge_card.card_no = card_no
            recharge_card.save()


class CleanData(BaseController):
    def get(self):
        for key in Users.objects.all():
            if 0 < key.amount < 99999:
                key.amount -= 1
                key.save()
        return self.render_json(data={})


class Recharge(BaseController):

    def get(self):
        # 获取参数
        did = self.get_argument('did', '')
        card_no = self.get_argument('card_no', '')
        if check_param([did, card_no]):
            self.render_json(code=10003, msg='参数不全')
            return
        user = Users.objects.filter(did=did).first()
        if not user:
            user = Users.objects.create(did=did)
        card = RechargeCard.objects.filter(card_no=card_no, state=0).first()
        if not card:
            self.render_json(code=10003, msg='卡已失效')
            return
        user.amount += card.amount
        user.save()
        card.state = 1
        card.did = user.did
        card.save()
        encrypt_data = encrept(json.dumps(user.to_dict()))
        self.render_json(data=encrypt_data)
        return
